package com.ls.config.shiro;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;

@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            boolean result = false;

            AuthenticationAPI authentication = getAnnotation(handlerMethod, AuthenticationAPI.class);
            if (authentication != null) {
                result = loginCheck(request, response); // 登录检查
                if (!result) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 登录检查
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    private boolean loginCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        OperSession session = (OperSession) request.getAttribute(LoginFilter.HTTP_ATTR_SESSION_KEY);
//        if (session == null || session.getOper() == null) {
//            // 用户会话过期，将返回错误码
//            response.setContentType("text/plain;charset=UTF-8");
//            ResultCode errorCode = ResultCode.SESSION_EXPIRED;
//            JsonCommon result = new JsonCommon(String.valueOf(errorCode.code()), errorCode.message());
//            response.getWriter().write(JSONObject.toJsonString(result));
//            return false;
//        }
        return true;
    }

    /**
     * 判断annotation是否存在
     *
     * @param handlerMethod
     * @param clazz annotation
     * @return
     */
    private <T extends Annotation> T getAnnotation(HandlerMethod handlerMethod, Class<T> clazz) {
        T annotation = handlerMethod.getMethodAnnotation(clazz);
        if (annotation != null) { // 方法的annotation不为空，直接返回
            return annotation;
        }
        annotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), clazz);
        return annotation;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
